﻿using Aliyun.OSS;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.BlobStoring;
using Volo.Abp.DependencyInjection;
using WMSSystem.YJ.DTO.Input;
using WMSSystem.YJ.Interface;

namespace WMSSystem.YJ
{
    public class FileAppService : IFileAppService, ITransientDependency
    {
        private readonly IConfiguration _configuration;
        private readonly QiniuOptions _qiniuOptions;

        public FileAppService(
            IConfiguration configuration,
            IOptions<QiniuOptions> qiniuOptions)
        {
            _configuration = configuration;
            _qiniuOptions = qiniuOptions.Value;
        }
        public Task DeleteFileFromQiniuAsync(string fileName)
        {
            throw new NotImplementedException();
        }

        public Task<byte[]> DownloadFileFromQiniuAsync(string fileName)
        {
            throw new NotImplementedException();
        }

        public Task<string> GetQiniuUploadTokenAsync()
        {
            throw new NotImplementedException();
        }

        public async Task<string> UploadFileToQiniuAsync(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                throw new ArgumentException("请选择有效的文件");
            }

            // 校验文件类型
            var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".txt", ".zip", ".rar" };
            var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
            if (!allowedExtensions.Contains(fileExtension))
            {
                throw new ArgumentException("不支持的文件格式");
            }

            // 校验文件大小（10MB）
            if (file.Length > 10 * 1024 * 1024)
            {
                throw new ArgumentException("文件大小不能超过10MB");
            }

            // 生成唯一文件名
            var fileName = $"files/{DateTime.Now:yyyyMMddHHmmssfff}_{Guid.NewGuid()}{fileExtension}";

            // 读取文件内容
            using var stream = file.OpenReadStream();
            var fileBytes = new byte[file.Length];
            await stream.ReadAsync(fileBytes, 0, (int)file.Length);

            // 创建七牛云配置
            var config = new Config();
            config.Zone = Zone.ZONE_CN_North; // 根据您的存储空间所在区域选择
            config.UseHttps = true;
            config.UseCdnDomains = true;

            // 创建七牛云上传管理器
            var uploadManager = new UploadManager(config);
            var mac = new Mac(_qiniuOptions.AccessKey, _qiniuOptions.SecretKey);
            var putPolicy = new PutPolicy();
            putPolicy.Scope = _qiniuOptions.Bucket;
            putPolicy.SetExpires(3600); // 1小时过期
            var uploadToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            // 创建上传额外参数
            var putExtra = new PutExtra();

            // 上传文件
            var result = await Task.Run(() => uploadManager.UploadData(fileBytes, fileName, uploadToken, putExtra));

            if (result.Code == 200)
            {
                // 返回文件访问URL
                return $"http://{_qiniuOptions.Domain}/{fileName}";
            }
            else
            {
                throw new Exception($"文件上传失败: {result.Text}");
            }
        }
    }
}
